<?php

namespace app\api\controller;

// use think\Log;
use app\service\WechatServie;
use EasyWeChat\Message\Text;

class Wxmsg extends Common
{
    public function index()
    {

        $app = (new WechatServie())->app();
        // 从项目实例中得到服务端应用实例。
        $server = $app->server;
        $message = $server->getMessage();
        // Log::write($message);exit;

        $openid = $message['FromUserName'];

        switch($message['MsgType']){
            case 'event':
                if($message['Event'] == 'subscribe' || ($message['Event'] == 'CLICK' && $message['EventKey'] == 'BIND')){
                    if($userid = cache('bindUnionid' . $openid)){
                        return $this->sendMessage("已成功绑定用户ID：" . $userid . "\n如有疑问，请在APP上联系客服", $openid);
                    }
                    $userid = WechatServie::bindUnionid($openid);
                    if (!$userid) {
                        return $this->sendMessage("请使用当前微信账号重新登录『那蓝之恋APP』后再尝试绑定", $openid);
                    }
                    cache('bindUnionid' . $openid, $userid);
                    return $this->sendMessage("已成功绑定用户ID：" . $userid . "\n如有疑问，请在APP上联系客服", $openid);
                }
                break;
            default:
                $content = $message['Content'];

                if($content == '绑定'){
                    $userid = WechatServie::bindUnionid($openid);
                    if (!$userid) {
                        exit('');
                    }
                    return $this->sendMessage("已成功绑定用户ID：" . $userid . "\n如有疑问，请在APP上联系客服", $openid);
                }elseif(strpos($content, '客服') !== false){
                    return $this->sendMessage("如有疑问，请在『那蓝之恋APP』上联系客服\n公众号暂不支持联系客服", $openid);
                }
                return $this->sendMessage("欢迎使用『那蓝之恋APP』", $openid);
                break;
        }


    }


    /**
      * 回复消息
      */
    private function sendMessage($content, $openid)
    {
        $app = (new WechatServie())->app();
        $message = new Text(['content' => $content]);
        $app->staff->message($message)->to($openid)->send();
    }

}
